<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
include_once("../class/Action.class.php");
require_once("../islogin.php");

if ($isadmin!=1){
    header('Location: /');
    exit('权限不足！');
}
$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];

//页面配置
$nowPage = $_GET['page'] ?? 1;
if($nowPage<0){
    exit('page error');
}
$pageName = "用户列表";
$pageNum = 12;
$totalPage = 1;

//页面数据
$res = $user->getAllUsers($nowPage, $pageNum);

$totalPage = $res['totalPages'];


if (isset($_GET['del'])) {
    // 在这里执行删除操作
    $user->delUser($_GET['del']);

    $referrer = $_SERVER['HTTP_REFERER'];
    header("Location: $referrer");
    exit();
}
if (isset($_GET['resetpwd'])) {
    // 在这里执行删除操作
    $user->resetpwd($_GET['resetpwd']);

    $referrer = $_SERVER['HTTP_REFERER'];
    header("Location: $referrer");
    exit();
}
if (isset($_GET['gouid'])) {
    $Temp_u_token = json_decode($user->TempUidlogin($_GET['gouid']),true)['message'];

    setcookie("save_me_token", $_COOKIE['admin_token'], time() + (86400 * COOKIE_OVERDUE_DAY), "/");
    setcookie("u_token", $Temp_u_token, time() + (86400 * COOKIE_OVERDUE_DAY), "/");

    header("Location: /control/");
    exit();
}

if($_GET['so']){
    $searchKeyword = $_GET['so'] ?? ''; // 获取搜索关键词
    $totalPage = 1;
    $sodataArray = $user->getAllUsers(1,2000);
    $filteredResults = array_filter($sodataArray['user'], function($item) use ($searchKeyword) {
        return stripos($item['nickname'], $searchKeyword) !== false || stripos($item['blue_id'], $_GET['so']) !== false; // 不区分大小写的模糊匹配

    });
    //var_dump($filteredResults);exit;
    $filteredResults = array_values($filteredResults);  //编制索引
    $res['user'] = $filteredResults;

}


require_once('page.php');


function calculateAge($birthday) {
    if ($birthday==null){
        return '未知';
    }
    $birthDate = new DateTime($birthday);
    $currentDate = new DateTime();
    $age = $currentDate->diff($birthDate)->y;
    return $age;
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php require_once('head.php'); ?>
</head> 
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->

<?php require_once('menu.php'); ?>
    <div class="dashboard-main-wrapper">
        <?php require_once('top_navbar.php'); ?>
        <div class="dashboard-body">

            <div class="card overflow-hidden">
                <div class="card-body p-0 overflow-x-auto">
                    <table id="studentTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th class="fixed-width">
                                    <div class="form-check">
                                        <input class="form-check-input border-gray-200 rounded-4" type="checkbox" id="selectAll">
                                    </div>
                                </th>
                                    <th class="h6 text-gray-300">头像/昵称</th>
                                    <th class="h6 text-gray-300">小蓝书号</th>
                                    <th class="h6 text-gray-300">年龄</th>
                                    <th class="h6 text-gray-300">IP</th>
                                    <th class="h6 text-gray-300">地区</th>
                                    <th class="h6 text-gray-300">性别</th>
                                    <th class="h6 text-gray-300">手机号</th>
                                    <th class="h6 text-gray-300">用户权限</th>
                                    <th class="h6 text-gray-300">注册时间</th>
                                    <th class="h6 text-gray-300">主页</th>
                                    <th class="h6 text-gray-300">删除</th>
                                    <th class="h6 text-gray-300">改权</th>
                                    <th class="h6 text-gray-300">后台</th>
                                    <th class="h6 text-gray-300">密码</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php for ($i = 0; $i < count($res['user']); $i++) { ?>
                        <tr>
                            <td class="fixed-width">
                                <div class="form-check">
                                    <input class="form-check-input border-gray-200 rounded-4" type="checkbox">
                                </div>
                            </td>
                            <td>
                                <div class="flex-align gap-8">
                                    <img src="<?php echo '/' . ltrim($res['user'][$i]["avatar"] ?: '/data/avatar/default.jpg', '/'); ?>" alt="" class="w-40 h-40 rounded-circle">
                                    <span class="h6 mb-0 fw-medium text-gray-300"><?php echo $res['user'][$i]['nickname'];?></span>
                                </div>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo $res['user'][$i]['blue_id'];?></span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo calculateAge($res['user'][$i]['birthday']);?> 岁</span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo long2ip($res['user'][$i]['ip'])?></span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo getIpProvince($res['user'][$i]['ip'])?></span>
                            </td>
                            <td>
                                    <span class="text-13 py-2 px-8
                                        <?php echo $res['user'][$i]['gender'] == 0 ? 'bg-pink text-pink-600' : 'bg-main text-main-600'; ?>
                                        d-inline-flex align-items-center gap-8 rounded-pill">

                                        <span class="w-6 h-6
                                            <?php echo $res['user'][$i]['gender'] == 0 ? 'bg-pink-600' : 'bg-main-600'; ?>
                                            rounded-circle flex-shrink-0"></span>

                                        <?php
                                        if ($res['user'][$i]['gender'] == 1) {
                                            echo '男';
                                        }elseif ($res['user'][$i]['gender'] == '0') {
                                            echo '女';
                                        }else{
                                            echo '无';
                                        }
                                        ?>


                                    </span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo $res['user'][$i]['phone']?></span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php
                                    switch ($res['user'][$i]['u_type']) {
                                        case 1:
                                            echo '<span class="text-13 py-2 px-8 bg-main-50 text-main-600 d-inline-flex align-items-center gap-8 rounded-pill">
                                                <span class="w-6 h-6 bg-main-600 rounded-circle flex-shrink-0"></span>
                                                管理员
                                            </span>';
                                            break;
                                        case 2:
                                            echo '<span class="text-13 py-2 px-8 bg-success-50 text-success-600 d-inline-flex align-items-center gap-8 rounded-pill">
                                                <span class="w-6 h-6 bg-success-600 rounded-circle flex-shrink-0"></span>
                                                用户
                                            </span>';
                                            break;
                                        case 3:
                                            echo '<span class="text-13 py-2 px-8 bg-purple-50 text-purple-600 d-inline-flex align-items-center gap-8 rounded-pill">
                                                <span class="w-6 h-6 bg-purple-600 rounded-circle flex-shrink-0"></span>
                                                审查官
                                            </span>';
                                            break;
                                        case 0:
                                            echo '<span class="text-13 py-2 px-8 bg-warning-50 text-warning-600 d-inline-flex align-items-center gap-8 rounded-pill">
                                                <span class="w-6 h-6 bg-warning-600 rounded-circle flex-shrink-0"></span>
                                                机器人
                                            </span>';
                                            break;
                                        default:
                                            echo "未知类型";
                                    }
                                    ?></span>
                            </td>
                            <td>
                                <span class="h6 mb-0 fw-medium text-gray-300"><?php echo formatTimestampToDate($res['user'][$i]['reg_time'])?></span>
                            </td>
                            <td>
                                <a href="/profile.php?id=<?php echo $res['user'][$i]['user_id'];?>" class="bg-main-50 text-main-600 py-2 px-14 rounded-pill hover-bg-main-600 hover-text-white"><i class="ph ph-eye"></i></a>
                            </td>
                            <td>
                                <a onclick="return confirm('确定要删除这个用户吗？不可恢复！删除后将连其他表的该UID一同删除清空！若该用户权限为管理员不可删除！');" href="?del=<?php echo $res['user'][$i]['user_id'];?>" class="bg-danger-50 text-danger-600 py-2 px-14 rounded-pill hover-bg-danger-600 hover-text-white"><i class="ph ph-user-minus"></i></a>
                            </td>
                            <td>
                                <a href="user_type.php?uid=<?php echo $res['user'][$i]['user_id'];?>" class="bg-purple-50 text-purple-600 py-2 px-14 rounded-pill hover-bg-purple-600 hover-text-white"><i class="ph ph-apple-podcasts-logo"></i></a>
                            </td>
                            <td>
                                <a href="?gouid=<?php echo $res['user'][$i]['user_id'];?>" class="bg-main-two-50 text-main-two-600 py-2 px-14 rounded-pill hover-bg-main-two-600 hover-text-white"><i class="ph ph-game-controller"></i></a>
                            </td>
                            <td>
                                <a onclick="return confirm('确定要将该用户的密码重置为123123吗?');" href="?resetpwd=<?php echo $res['user'][$i]['user_id'];?>" class="bg-primary-50 text-primary-600 py-2 px-14 rounded-pill hover-bg-primary-600 hover-text-white"><i class="ph ph-numpad"></i></a>
                            </td>
                        </tr>
                        <?php } ?>



                        </tbody>
                    </table>
                </div>
                <div class="card-footer flex-between flex-wrap">
                    <span class="text-gray-900">共 <?php echo $res['totalCount'];?> 条数据 <?php echo $nowPage?>/<?php echo $totalPage?> 页</span>
                    <ul class="pagination flex-align flex-wrap">
                        <?php if($totalPage>1){?>
                                <?php include 'pagination.php'; ?>
                        <?php }?>
                    </ul>
                </div>
            </div>
            
        </div>
        <?php require_once('footer.php'); ?>
    </div>


<?php require_once('foot.php'); ?>


    <script>


        function downloadCSV(data) {
            const csv = data.map(row => Object.values(row).join(',')).join('\n');
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'info.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }

        function downloadJSON(data) {
            const json = JSON.stringify(data, null, 2);
            const blob = new Blob([json], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'info.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        // ========================== Export Js End ==============================
    
        // Table Header Checkbox checked all js Start
        $('#selectAll').on('change', function () {
            $('.form-check .form-check-input').prop('checked', $(this).prop('checked')); 
        }); 
    
        // Data Tables
        new DataTable('#studentTable', {
            searching: false,
            lengthChange: false,
            info: false,   // Bottom Left Text => Showing 1 to 10 of 12 entries
            paging: false, // Pagination False
            "columnDefs": [
                { "orderable": false, "targets": [0, 6] } // Disables sorting on the 7th column (index 6)
            ]
        });
    </script>

    </body>
</html>